package com.dragon.modules.yuegou.service.impl.live;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.client.wechat_mini.common.MiniConfig;
import com.dragon.modules.yuegou.client.wechat_mini.model.GetGood;
import com.dragon.modules.yuegou.client.wechat_mini.model.GoodsInfo;
import com.dragon.modules.yuegou.client.wechat_mini.request.GetGoodsWareHouseRequest;
import com.dragon.modules.yuegou.client.wechat_mini.request.GoodsAddRequest;
import com.dragon.modules.yuegou.client.wechat_mini.request.GoodsDeleteRequest;
import com.dragon.modules.yuegou.client.wechat_mini.response.GetGoodsWareHouseResponse;
import com.dragon.modules.yuegou.client.wechat_mini.response.GoodsAddResponse;
import com.dragon.modules.yuegou.client.wechat_mini.service.MiniService;
import com.dragon.modules.yuegou.client.wechat_mini.service.impl.MiniServiceImpl;
import com.dragon.modules.yuegou.entity.live.BroadcastSpuEntity;
import com.dragon.modules.yuegou.entity.live.ReviewSpuEntity;
import com.dragon.modules.yuegou.entity.product.SpuEntity;
import com.dragon.modules.yuegou.enums.code.LiveCode;
import com.dragon.modules.yuegou.mapper.live.ReviewSpuMapper;
import com.dragon.modules.yuegou.model.live.ReviewSpu;
import com.dragon.modules.yuegou.model.system.Application;
import com.dragon.modules.yuegou.properties.LiveProperties;
import com.dragon.modules.yuegou.query.live.BroadcastSpuQuery;
import com.dragon.modules.yuegou.query.live.ReviewSpuQuery;
import com.dragon.modules.yuegou.service.live.BroadcastSpuService;
import com.dragon.modules.yuegou.service.live.ReviewSpuService;
import com.dragon.modules.yuegou.service.product.SpuService;
import com.dragon.modules.yuegou.service.system.ApplicationService;
import com.dragon.modules.yuegou.utils.PageToResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品送审表 服务实现
 *
 * @author ZSH
 * @date 2020-06-12 09:57:51
 * @version 2.0
 */
@Service("liveReviewSpuService")
public class ReviewSpuServiceImpl
		extends ServiceImpl<ReviewSpuMapper, ReviewSpuEntity>
		implements ReviewSpuService {
	
	
	@Autowired
	private ApplicationService applicationService;
	
	@Autowired
	private SpuService spuService;
	
	@Autowired
	private LiveProperties liveProperties;
	
	@Autowired
	private BroadcastSpuService broadcastSpuService;
	
	@Override
	public List<ReviewSpu> goodsList(String broadcastId) {
		return baseMapper.goodsList(broadcastId);
	}
	
	@Override
	public void sygSpuStatus() {
		//查询绑定商品中所有的商圈
		List<String> busdIds = baseMapper.busdList();
		if (CollectionUtils.isEmpty(busdIds)) {
			return;
		}
		for (String busdId : busdIds) {
			ReviewSpuQuery query = new ReviewSpuQuery();
			List<String> vals = new ArrayList<>();
			vals.add("3");
			vals.add("2");
			query.status().notIn(vals);
			query.setBusdId(busdId);
			List<ReviewSpuEntity> list = list(query.toQueryWrapper());
			if (CollectionUtils.isEmpty(list)) {
				continue;
			}
			
			// 查询application信息
			Application application = applicationService.getOriginalId(busdId);
			MiniService service = new MiniServiceImpl(new MiniConfig(application.getAppid(), application.getAppsecret()));
			
			//提取所有商品Id
			List<Integer> goodsIds = list.stream().map(broad -> Integer.parseInt(broad.getGoodsId())).collect(Collectors.toList());
			
			GetGoodsWareHouseRequest request = new GetGoodsWareHouseRequest();
			request.setGoodsIds(goodsIds);
			GetGoodsWareHouseResponse response = service.live().getGoodsWareHouse(request);
			//修改商品审核信息
			for (ReviewSpuEntity spu : list) {
				for (GetGood good : response.getGoods()) {
					if (good.getGoodsId()!=null && spu.getGoodsId().equals(good.getGoodsId().toString())) {
						spu.setStatus(good.getAuditStatus().toString());
						baseMapper.updateById(spu);
					}
				}
			}
		}
	}

	@Override
	public IPage<ReviewSpu> reviewSpuList(PageRequest page, String name, String status, String busdId) {
		ReviewSpuQuery query = new ReviewSpuQuery();
		query.name().like(name);
		query.setBusdId(busdId);
		if (StringUtils.isNotEmpty(status)) {
			query.setStatus(status);
		}
		QueryWrapper<ReviewSpuEntity> wrapper = query.toQueryWrapper();
		wrapper.orderByDesc(ReviewSpu.COL_ID);

		return page(PageToResultUtils.resultToPage(page), wrapper);
	}

	@Override
	@Transactional
	public void deleteReviewSpu(String id) {
		ReviewSpuEntity spu = getById(id);
		//删除审核商品记录
		removeById(spu.getId());
		//删除所有商品绑定直播间关系
		BroadcastSpuQuery query = new BroadcastSpuQuery();
		query.setReviewId(spu.getId());
		List<BroadcastSpuEntity> list = broadcastSpuService.list(query.toQueryWrapper());
		if (CollectionUtils.isNotEmpty(list)) {
			broadcastSpuService.removeBatchByIds(list.stream().map(BroadcastSpuEntity::getId).collect(Collectors.toList()));
		}
		
		// 查询application信息
		Application application = applicationService.getOriginalId(spu.getBusdId());
		MiniService service = new MiniServiceImpl(new MiniConfig(application.getAppid(), application.getAppsecret()));
		GoodsDeleteRequest request = new GoodsDeleteRequest();
		request.setGoodsId(spu.getGoodsId());
		service.live().goodsDelete(request);
	}
	
	@Override
	public void createReviewSpu(ReviewSpu reviewSpu) {
		SpuEntity spu = spuService.getById(reviewSpu.getSpuId());

		String format = String.format(liveProperties.getGoodsurl(), spu.getId(), reviewSpu.getBusdId());
		//组装送审信息
		GoodsAddRequest request = new GoodsAddRequest();
		GoodsInfo goodsInfo = new GoodsInfo();
		goodsInfo.setCoverImgUrl(reviewSpu.getCoverImgUrlMedia());
		goodsInfo.setName(spu.getTitle());
		goodsInfo.setPriceType(2);
		goodsInfo.setPrice(spu.getMinPrice());
		goodsInfo.setPrice2(spu.getMaxPrice());
		goodsInfo.setUrl(format);
		request.setGoodsInfo(goodsInfo);


		// 查询application信息
		Application application = applicationService.getOriginalId(spu.getBusdId());
		MiniService service = new MiniServiceImpl(new MiniConfig(application.getAppid(), application.getAppsecret()));

		//直播间商品送审
		GoodsAddResponse response = service.live().goodsAdd(request);
		if (response !=null &&response.getErrcode() !=null && response.getErrcode() !=0){
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),response.getErrmsg());
		}
		// 创建商品信息
		reviewSpu.setAuditId(response.getAuditId());
		reviewSpu.setGoodsId(response.getGoodsId());
		reviewSpu.setStatus("0");
		reviewSpu.setName(spu.getTitle());
		reviewSpu.setPrice(spu.getMinPrice());
		reviewSpu.setPrice2(spu.getMaxPrice());
		reviewSpu.setPriceType("2");
		reviewSpu.setUrl(format);
		baseMapper.insert(reviewSpu);
	}
}